package cn.steam.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author riven zhang
 * @since 2021/9/10 11:02
 */
public class ExcelUtil {

    public static <T> List<T> read(String path, Class<T> clazz) {
        ExcelReaderBuilder read = EasyExcel.read(path);
        List<Map<Integer, String>> list = read.doReadAllSync();
        Field[] fields = clazz.getDeclaredFields();
        ArrayList<T> res = new ArrayList<>(list.size());
        System.out.println("list.size() = " + list.size());
        for (Map<Integer, String> map : list) {
            try {
                T t = clazz.newInstance();
                for (int i = 0; i < fields.length; i++) {
                    fields[i].setAccessible(true);
                    fields[i].set(t, map.get(i));
                }
                res.add(t);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return res;
    }

    public static String[][] read(InputStream path) {
        ExcelReaderBuilder read = EasyExcel.read(path);
        List<Map<Integer, String>> list = read.doReadAllSync();
        int r = list.size();
        int c = list.get(0).size();
        String[][] arr = new String[r][c];
        for (int i = 0; i < r; i++) {
            Map<Integer, String> map = list.get(i);
            for (int j = 0; j < c; j++) {
                arr[i][j] = map.get(j);
            }
        }
        return arr;
    }


}


